package com.czr.dao.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czr.dao.entity.*;
import com.czr.dao.mapper.CzrHuidaMapper;
import com.czr.dao.mapper.CzrSurveysMapper;
import com.czr.dao.service.CzrHuidaService;
import com.czr.dao.service.CzrSurveysService;
import com.czr.dto.HuidaParam;
import com.czr.dto.Search;
import com.czr.dto.SurveysParam;
import com.czr.util.PageUtil;
import com.czr.vo.CzrHuidaVo;
import com.czr.vo.Result;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.sql.ResultSetMetaData;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 新闻资讯 服务实现类
 * </p>
 */
@Service
public class CzrHuidaServiceImpl extends ServiceImpl<CzrHuidaMapper, CzrHuida> implements CzrHuidaService {


    @Autowired
    CzrSurveysMapper czrSurveysMapper;
    @Autowired
    CzrHuidaMapper czrHuidaMapper;


    @Override
    public Result<Object> getList(Search search) throws Exception {
        Page<CzrHuida> page = new Page<>();
        page.setSize(search.getSize());
        page.setCurrent(search.getCurrent());
        LambdaQueryWrapper<CzrHuida> ew = new LambdaQueryWrapper<>();
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(search.getKeyword())) {
            ew.like(CzrHuida::getName, search.getKeyword());
        }
        ew.orderByDesc(CzrHuida::getInsertTime);
        page = this.getBaseMapper().selectPage(page, ew);
        JSONArray array = new JSONArray();
        for (CzrHuida czrHuida : page.getRecords()) {
            CzrHuidaVo czrHuidaVo = new CzrHuidaVo();
            BeanUtils.copyProperties(czrHuida, czrHuidaVo);
            czrHuidaVo.setSurveysName(czrSurveysMapper.selectById(czrHuida.getSurveysId()).getName());
            array.add(czrHuidaVo);
        }
        JSONObject object = PageUtil.getPage(array, page);
        return Result.data(object);

    }

    @Override
    public void downHuidaList(Long id, HttpServletResponse response) throws Exception {
        try {

            List<CzrHuida> czrHuidaList = czrHuidaMapper.getList(id);
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("CzrHuidaData");

            // 写入表头
            Row headerRow = sheet.createRow(0);

            Cell cell = headerRow.createCell(0);
            cell.setCellValue("姓名");
            Cell cell1 = headerRow.createCell(1);
            cell1.setCellValue("性别");
            Cell cell2 = headerRow.createCell(2);
            cell2.setCellValue("年龄");
            Cell cell3 = headerRow.createCell(3);
            cell3.setCellValue("电话");
            Cell cell4 = headerRow.createCell(4);
            cell4.setCellValue("微信号");
            Cell cell5 = headerRow.createCell(5);
            cell5.setCellValue("邮箱");

            if (!czrHuidaList.isEmpty()){
                List<CzrQuestions> czrQuestionsList = czrSurveysMapper.getQuestions(Math.toIntExact(id));
                for (int i = 1; i <= czrQuestionsList.size(); i++) {
                    Cell cells = headerRow.createCell(i + 5);
                    cells.setCellValue( czrQuestionsList.get(i-1).getText());
                }
            }
            // 写入数据
            int rowIndex = 1;
            while (rowIndex <= czrHuidaList.size()) {
                CzrHuida czrHuida = czrHuidaList.get(rowIndex - 1);
                Row dataRow = sheet.createRow(rowIndex++);
                Cell celln1 = dataRow.createCell(0);
                celln1.setCellValue(czrHuida.getName());
                Cell celln2 = dataRow.createCell(1);
                if(!StringUtils.isEmpty(czrHuida.getSex()) && czrHuida.getSex()==1){
                    celln2.setCellValue("男");
                }else if(!StringUtils.isEmpty(czrHuida.getSex()) && czrHuida.getSex()==2){
                    celln2.setCellValue("女");
                }
                Cell celln3 = dataRow.createCell(2);
                celln3.setCellValue(czrHuida.getAge());
                Cell celln4 = dataRow.createCell(3);
                celln4.setCellValue(czrHuida.getPhone());
                Cell celln5 = dataRow.createCell(4);
                celln5.setCellValue(czrHuida.getWx());
                Cell celln6 = dataRow.createCell(5);
                celln6.setCellValue(czrHuida.getEmail());
                List<CzrQuestions> czrQuestionsList = czrSurveysMapper.getQuestions(Math.toIntExact(czrHuida.getSurveysId()));
                for (int i = 1; i <= czrQuestionsList.size(); i++) {
                    Cell cells = dataRow.createCell(i + 5);
                    CzrAnswers czrAnswers = czrSurveysMapper.getAnswerInfoById(czrHuida.getId(), czrQuestionsList.get(i - 1).getId());
                    if (czrQuestionsList.get(i - 1).getType() == 1) {
                        String txt = "";
                        if (!StringUtils.isEmpty(czrAnswers.getOptionId())) {
                            CzrOptions czrOptions = czrSurveysMapper.getOptionInfo(Long.parseLong(czrAnswers.getOptionId()));
                            txt = czrOptions.getText();
                        }
                        cells.setCellValue(txt);
                    } else if (czrQuestionsList.get(i - 1).getType() == 2) {
                        String txt = "";
                        if (!StringUtils.isEmpty(czrAnswers.getOptionId())) {
                            String[] split = czrAnswers.getOptionId().split(",");
                            for (int k = 0; k < split.length; k++) {
                                CzrOptions czrOptions = czrSurveysMapper.getOptionInfo(Long.parseLong(split[k]));
                                if (k == split.length - 1) {
                                    txt += czrOptions.getText();
                                } else {
                                    txt += czrOptions.getText() + ",";
                                }
                            }
                        }
                        cells.setCellValue(txt);
                    } else if (czrQuestionsList.get(i - 1).getType() == 3) {
                        cells.setCellValue(czrAnswers.getTextAnswer());
                    }
                }
            }
            // 准备将Excel写入HTTP响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=CzrHuidaData.xlsx");
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
